package com.gyj.Test.Other;

import com.gyj.modules.user.model.UserInfo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Gao on 2018/5/12.
 */
public class GroupByFiled {

    //最后结果，发现集合大小由4变成3。集合根据特定条件被成功分组
    public static void main(String[] args) throws Exception {
        List<UserInfo> billingList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        UserInfo a1 = new UserInfo();
        a1.setId(1);
        a1.setName("GLOBAL_1_MOTHER");
        a1.setCreateTime(sdf.parse("2015/01/01"));
        billingList.add(a1);
        UserInfo a2 = new UserInfo();
        a2.setId(2);
        a2.setName("GLOBAL_1_MOTHER");
        a2.setCreateTime(sdf.parse("2015/02/01"));
        billingList.add(a2);
        UserInfo a3 = new UserInfo();
        a3.setId(3);
        a3.setName("GLOBAL_1_MOTHER");
        a3.setCreateTime(sdf.parse("2015/01/01"));
        billingList.add(a3);
        UserInfo a4 = new UserInfo();
        a4.setId(4);
        a4.setName("GLOBAL_1_MOTHER");
        a4.setCreateTime(sdf.parse("2016/01/01"));
        billingList.add(a4);

        groupByFiled(billingList);
    }


    private static Map<String, List<UserInfo>> groupByFiled(List<UserInfo> billingList) throws Exception {
        Map<String, List<UserInfo>> resultMap = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); //按照时间进行聚类分组
        try {
            for (UserInfo user : billingList) {
                String key = sdf.format(user.getCreateTime());
                if (resultMap.containsKey(key)) {
                    //map中已存在，将该数据存放到同一个key的map中
                    resultMap.get(key).add(user);
                } else {
                    //map中不存在，新建key，用来存放数据
                    List<UserInfo> tmpList = new ArrayList<>();
                    tmpList.add(user);
                    resultMap.put(key, tmpList);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultMap;
    }
}
